<template>
  <div class="container">
    <!-- 筛选区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="结算状态">
        <el-select v-model="searchForm.settlementStatus" placeholder="请选择">
          <el-option label="未结算" value="未结算"></el-option>
          <el-option label="已结算" value="已结算"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建日期">
        <el-date-picker
          v-model="searchForm.createDate"
          type="daterange"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-input v-model="searchForm.keyword" placeholder="请输入关键词搜索"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 新增操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleBatchDelete"
        >批量删除</el-button>
      </el-col>
    </el-row>



    <!-- 表格区域 -->
    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="statementNo" label="对账单号"></el-table-column>
      <el-table-column prop="carrier" label="承运商"></el-table-column>
      <el-table-column prop="settlementStatus" label="结算状态"></el-table-column>
      <!-- 👇 修改以下四列的 prop 属性 👇 -->
      <el-table-column prop="totalOrders" label="订单总数量"></el-table-column>
      <el-table-column prop="goodsQuantity" label="货物数量"></el-table-column>
      <el-table-column prop="totalVolume" label="货物总体积"></el-table-column>
      <el-table-column prop="totalWeight" label="货物总重量"></el-table-column>
      <el-table-column prop="payableAmount" label="应付总金额(元)"></el-table-column>
      <el-table-column prop="actualAmount" label="实付总金额(元)"></el-table-column>
      <el-table-column prop="creator" label="创建人"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 点击编辑弹出编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" @close="handleDialogClose">
      <el-form ref="editForm" :model="editForm" :rules="editFormRules" label-width="120px">
        <el-form-item v-if="editForm.id" label="ID" prop="id">
          <el-input v-model="editForm.id" disabled/>
        </el-form-item>
        <el-form-item label="对账单号" prop="statementNo">
          <el-input v-model="editForm.statementNo" placeholder="请输入对账单号"/>
        </el-form-item>
        <el-form-item label="承运商" prop="carrier">
          <el-input v-model="editForm.carrier" placeholder="请输入承运商"/>
        </el-form-item>
        <el-form-item label="结算状态" prop="settlementStatus">
          <el-select v-model="editForm.settlementStatus" placeholder="请选择结算状态" style="width: 100%">
            <el-option label="未结算" value="未结算"></el-option>
            <el-option label="已结算" value="已结算"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单总数量" prop="totalOrders">
          <el-input-number v-model="editForm.totalOrders" :min="0" controls-position="right" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="货物数量" prop="goodsQuantity">
          <el-input-number v-model="editForm.goodsQuantity" :min="0" controls-position="right" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="货物总体积" prop="totalVolume">
          <el-input-number v-model="editForm.totalVolume" :min="0" controls-position="right" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="货物总重量" prop="totalWeight">
          <el-input-number v-model="editForm.totalWeight" :min="0" controls-position="right" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="应付总金额" prop="payableAmount">
          <el-input-number v-model="editForm.payableAmount" :min="0" controls-position="right" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="实付总金额" prop="actualAmount">
          <el-input-number v-model="editForm.actualAmount" :min="0" controls-position="right" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="editForm.creator" placeholder="请输入创建人" disabled/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
  </div>
</template>

<script>
import { list ,del,update} from '@/api/tms/pra/pra'
import {delAll} from "@/api/tms/complete/all";


export default {
  data() {
    return {
      searchForm: {
        settlementStatus: '',
        createDate: [],
        keyword: '',
      },
      tableData: [], // 表格数据，这里无实际数据，可根据需求从后端获取
      currentPage: 1,
      pageSize: 10,
      total: 0, // 总条数
      multiple: true,
      selectedRows: [],


      // 编辑数据
      dialogVisible: false,
      dialogTitle: '编辑对账单',
      editForm: {
        id: null,
        statementNo: '',
        carrier: '',
        settlementStatus: '',
        totalOrders: 0,
        goodsQuantity: 0,
        totalVolume: 0,
        totalWeight: 0,
        payableAmount: 0,
        actualAmount: 0,
        creator: ''
      },
      //校验规则
      editFormRules: {
        statementNo: [{ required: true, message: '请输入对账单号', trigger: 'blur' }],
        carrier: [{ required: true, message: '请输入承运商', trigger: 'blur' }],
        settlementStatus: [{ required: true, message: '请选择结算状态', trigger: 'change' }],
        totalOrders: [{ required: true, message: '请输入订单总数量', trigger: 'blur' }],
        payableAmount: [{ required: true, message: '请输入应付总金额', trigger: 'blur' }]
      }
    };
  },
  created() {
    this.getTableData();
  },
  methods: {
    search() {
      // 搜索逻辑，可根据searchForm中的参数请求后端数据
      this.currentPage = 1; // 搜索时重置到第一页
      this.getTableData(); // 调用获取数据方法
    },
    reset() {
      // 重置表单
      this.searchForm = {
        settlementStatus: '',
        createDate: [],
        keyword: '',
      };
      this.currentPage = 1;
      this.getTableData(); // 重置后重新获取数据
    },

    // 获取表格数据
    getTableData() {
      // 构造请求参数
      const query = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        settlementStatus: this.searchForm.settlementStatus,
        keyword: this.searchForm.keyword,
      }
      // 日期范围处理
      if (this.searchForm.createDate && this.searchForm.createDate.length === 2) {
        // 开始日期保持不变
        const startDate = new Date(this.searchForm.createDate[0])
        const format = (date) => {
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          return `${year}-${month}-${day}`
        }

        query.beginTime = format(startDate)

        // 结束日期加一天，确保包含选择的那一天
        const endDate = new Date(this.searchForm.createDate[1])
        endDate.setDate(endDate.getDate() + 1)
        query.endTime = format(endDate)
      }
      // 显示加载状态
      this.loading = true;
      // 调用API获取数据
      list(query).then(response => {
        this.tableData = response.rows; // 表格数据
        this.total = response.total;    // 总条数
        this.loading = false;
      }).catch(error => {
        console.error('获取数据失败:', error);
        this.loading = false;
      });
    },
    // 每页条数改变时的回调
    handleSizeChange(val) {
      this.pageSize = val;
      this.getTableData(); // 改变每页条数时重新获取数据
    },
    // 当前页改变时的回调
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getTableData(); // 改变页码时重新获取数据
    },
    handleAdd() {
      // 新增操作逻辑
    },

    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择需要删除的记录')
        return
      }

      // 获取选中行的ID数组
      const ids = this.selectedRows.map(row => row.id)
      const statements = this.selectedRows.map(row => row.statementNo).join(',')

      this.$confirm(`确定要删除选中的对账单"${statements}"吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除接口，传递ID数组
        del(ids).then(response => {
          this.$message.success('批量删除成功')
          this.getTableData() // 重新加载数据
          this.selectedRows = [] // 清空选中状态
          this.multiple = true // 禁用批量删除按钮
        }).catch(error => {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败，请重试')
        })
      }).catch(() => {
        // 用户取消删除
        this.$message.info('已取消删除')
      })
    },
    // 处理选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
      // 当选中行数量大于0时启用批量删除按钮
      this.multiple = selection.length === 0
    },

    handleEdit(row) {
      // 编辑操作逻辑
      this.dialogTitle = '编辑对账单'
      this.dialogVisible = true
      // 回显数据到表单
      this.editForm = { ...row }
    },

    // 提交编辑表单
    submitEditForm() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 调用编辑接口
          update(this.editForm).then(response => {
            this.$message.success('编辑成功')
            this.dialogVisible = false
            this.getTableData() // 刷新表格
            this.loading = false
          }).catch(error => {
            console.error('编辑失败:', error)
            this.$message.error('编辑失败，请重试')
            this.loading = false
          })
        }
      })
    },
    // 关闭时重置表单
    handleDialogClose() {
      this.$refs.editForm.resetFields() // 关闭时重置表单
    },
    handleDelete(row) {
      // 删除操作逻辑
      this.$confirm(`确定要删除对账单"${row.statementNo}"吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除接口，传递单个ID
        del([row.id]).then(response => {
          this.$message.success('删除成功')
          this.getTableData() // 重新加载数据
        }).catch(error => {
          console.error('删除失败:', error)
          this.$message.error('删除失败，请重试')
        })
      }).catch(() => {
        // 用户取消删除
        this.$message.info('已取消删除')
      })
    },
  },
};
</script>

<style scoped>
.container {
  padding: 20px;
}
.search-form {
  margin-bottom: 20px;
}
</style>
